<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    @ok="handleSubmit"
    :title="LWM2MService.name"
    :destroyOnClose="true"
    :closeFunc="close"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
  >
    <InputList
      inputTitle="实例列表"
      :initInputDataList="list"
      @get-input-data-list="push"
      :dataChange="list"
    />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import InputList from '/@/components/thingsborad/sharedComponents/modules/InputList.vue';
  import { getLWM2MList } from '/@/api/thingsborad/profile/deviceProfile/deviceProfile';
  import { useMessage } from '/@/hooks/web/useMessage';
  import _ from 'lodash';
  const emits = defineEmits(['get-instance']);
  let LWM2MService = ref<any>('');
  let list = ref<any>([]);
  let lwm2mList = ref<any>([]);
  //请求lwm2m的参数
  let params = ref<any>({
    pageSize: 50,
    page: 0,
    sortProperty: 'id',
    sortOrder: 'ASC',
  });
  const { createMessage } = useMessage();
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    LWM2MService.value = data;

    data.instances.map((item) => {
      list.value.push({ text: item.id });
    });
  });
  async function selectLWM2MList() {
    lwm2mList.value = [];
    try {
      let response = await getLWM2MList(params.value);
      lwm2mList.value = response;
    } catch (error) {
      console.error('获取LWM2M数据时报错：', error);
    }
  }
  function push(data: Array<any>) {
    let validatedData: any = [];
    let numberSet = new Set();
    data.forEach((item) => {
      let number = parseInt(item.text, 10);
      if (isNaN(number)) {
        createMessage.error('请输入数字');
      } else if (number > 65535) {
        createMessage.error('不能大于65535');
      } else {
        if (!numberSet.has(number)) {
          numberSet.add(number);
          validatedData.push({ text: number });
        }
      }
    });
    list.value = [];
    list.value = [...validatedData];
  }
  async function close() {
    list.value = [];
    return true;
  }
  async function handleSubmit() {
    await selectLWM2MList();
    let instance: any = {};
    lwm2mList.value.map((item) => {
      if (item.keyId === LWM2MService.value.keyId) {
        instance = _.cloneDeep(item.instances[0]);
      }
    });

    const objectMap = new Map(LWM2MService.value.instances.map((obj) => [obj.id, obj]));

    const targetIdSet = new Set(list.value.map((item) => item.text));

    const updatedArrayWithObjects: any = [];

    LWM2MService.value.instances.forEach((obj) => {
      if (targetIdSet.has(obj.id)) {
        updatedArrayWithObjects.push(_.cloneDeep(obj));
      } else {
      }
    });
    list.value.forEach((id) => {
      if (!objectMap.has(id.text)) {
        let temInstance = _.cloneDeep(instance);
        temInstance.id = id.text;

        temInstance.resources.map((item) => {
          item.keyName = item.keyName + String(id.text);
        });
        updatedArrayWithObjects.push(temInstance);
      }
    });

    LWM2MService.value.instances = updatedArrayWithObjects;

    emits('get-instance', LWM2MService.value);
    list.value = [];
    closeModal();
  }
</script>
